<?php
require_once "BaseAction.php";
require_once APPLICATION_PATH."/modules/event/lib/Sns.php";


class Event_CommentController extends TTEvent_Base_Action 
{
	public function init()
	{
		parent::init();
		//$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->layout->disableLayout();
	}
	
	public function indexAction()
	{
		exit();
	}
	
	public function saveAction()
	{
		
		$eid=(int)$this->_getParam("eid", 0);
		$user = $this->getUser();
		if ($eid==0)
		{
			exit();
		}
		$content=trim($this->_getParam("comment_content"));
		if ($content=="")
		{
			exit();
		}
		
		$event=$this->_helper->modelLoader->getEventInfo($eid);
		if ($event===false)
		{
			exit();
		}
		
		if (!$this->_helper->privacy->isCanAdd('comment', $eid, $user->uid))
		{
			exit();
		}
		
		if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) 
			$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
		else 
			$ip = $_SERVER["REMOTE_ADDR"];
		
		$c_model=$this->loadModel("Comment");
		$cid = (int)$this->_getParam('cid'); 
		if ($cid != 0) {
            $c = $c_model->getComment($cid);                
            if ( ! $c OR $c->ref != $eid OR $c->reply_to != 0) {
                exit();
            } 
            
        }
		
		$user=$this->getUser();
		
		$p = $this->_getParam('p', '');
		$page = $this->_getParam('page', 0);
		
		$data=array(
			"module"	=> 'event',
			"ref"	=> $eid,
			"uid"	=> $user->uid,
			"created"	=> time(),
			"content"	=> $content,
			"host"		=> $ip,
			"status"	=> 1,
			"format"	=> 0,
			"uname"		=> $user->name,
            "changed"   => time(),
            "reply_to"  => $cid
		);
		
		if($cid)
			$c_model->updateCommentChanged($cid);
		$cid=$c_model->insertComment($data); 
		
		//$this->sendLog('event/add/comment', $user->uid, $eid, $cid, $user->uid);
		$logevent = array(
            'action'        =>  'event/comment/add',
            'uid'           =>  $user->uid,
            'username'      =>  $user->name,
            'avatar'      	=>  $user->picture,
            'content'       =>  truncate_utf8($content, 70),
            'eid'           =>  $eid,
            'event_name'  	=>  $event->event_name,
            'created'       =>  time()
        );
		ThriftLogger::thrift_log_get_content($logevent);
		
		$eventModel = $this->loadModel('Event');
		$eventModel->update(array('changed'=>time()), 'eid='.$eid);
		
		$event = $this->_helper->modelLoader->getEventInfo($eid, false, false);
		
		//ThriftLogger::thrift_log_comment_create($user->uid, $cid, $content, time(), $event->view_privacy, $user->uid, $event->eid, $event->uid, $event->title);
		
		$this->deleteCache("event_comment_$eid".'_10');            
		$this->deleteCache("event_reply_$eid");
        $this->deleteCache("event_comment_$eid".'_20');

		$event=$this->_helper->modelLoader->getEventInfo($event->eid, false);

		$template = "view";
		if($p=='cover' && $event->short_cut!=""){
			$this->prepareView($event, 0, 10);
			$template = 'comment-list';
			
			$layout = Zend_Layout::getMvcInstance();
			$layout->getView()->setScriptPath(APPLICATION_PATH . '/modules/event/views/themes/'.$event->short_cut);
		}
		else{
			$this->prepareView($event, 0);
		}
		
		$this->render($template);
	}
	
	public function viewAction()
	{
		$eid=(int)$this->_getParam("eid", 0);
		$user = $this->getUser();
		if ($eid==0)
		{
			exit();
		}
		$p = $this->_getParam('p', '');
		$page = $this->_getParam('page', 0);
		
		$event=$this->_helper->modelLoader->getEventInfo($eid);
		if ($event===false)
		{
			exit();
		}
		
		$template = "view";
		if($p=='cover' && $event->short_cut!=""){
			$this->prepareView($event, $page, 10);
			$template = 'comment-list';
			
			$layout = Zend_Layout::getMvcInstance();
			$layout->getView()->setScriptPath(APPLICATION_PATH . '/modules/event/views/themes/'.$event->short_cut);
		}
		else{
			$this->prepareView($event, $page);
		}
		
		$this->render($template);
//		echo $this->_helper->eventCommon->getHtmlCommentList($event);
//		exit();
	}
	
	public function deleteAction()
	{
		$cid=(int)$this->_getParam("cid", 0);
		if ($cid==0)
		{
			exit();
		}
		$p = $this->_getParam('p', '');
		$page = $this->_getParam('page', 0);
		
		$c_model=$this->loadModel("Comment");
		$event=$c_model->getEventInfoFromComment($cid);
		if ($event===false)
		{
			exit();
		}
		
		$is_admin=$this->isAdmin();
		$is_mod=$this->isMod();
		$user=$this->getUser();
		$is_owner=($event->uid==$user->uid);
		
		if (!$is_admin && !$is_mod && !$is_owner)
		{
			exit();
		}
		
		$c=$c_model->getComment($cid);
		if($c){
			$isReply = ($c->reply_to != 0) ? TRUE : FALSE;
			
			//$this->sendLog('event/del/comment', $user->uid, $eid, $c->cid, $c->uid);
			$logevent = array(
	            'action'        =>  'event/comment/delete',
	            'cid'           =>  $c->cid,
	            'uid'           =>  $c->uid,
	            'username'      =>  $c->uname,
	            'modId'         =>  $user->uid,
	            'modName'       =>  $user->name,            
	            'eid'           =>  $event->eid,
	            'event_name'  	=>  $event->event_name,
	            'created'       =>  time()
	        );
	        ThriftLogger::thrift_log_get_content($logevent);
				
			$c_model->deleteComment($cid, $event->eid, $isReply);
			$event=$this->_helper->modelLoader->getEventInfo($event->eid, false);
			$this->deleteCache("event_comment_" . $event->eid.'_10');
			$this->deleteCache("event_reply_" . $event->eid);
            $this->deleteCache("event_comment_" . $event->eid.'_20');
			
//			if($is_owner)
//				ThriftLogger::thrift_log_comment_delete($event->eid, $event->uid, $event->event_name, $cid, $c->uid, $user->uid, time());
//			else if($is_admin || $is_mod){
//				ThriftLogger::thrift_log_comment_destroy($event->eid, $event->uid, $event->event_name, $cid, $c->uid, $user->uid, time());
//			}
		}
		
		$template = "view";
		if($p=='cover' && $event->short_cut!=""){
			$this->prepareView($event, $page, 10);
			$template = 'comment-list';
			
			$layout = Zend_Layout::getMvcInstance();
			$layout->getView()->setScriptPath(APPLICATION_PATH . '/modules/event/views/themes/'.$event->short_cut);
		}
		else{
			$this->prepareView($event, $page);
		}
		
		$this->render($template);
	}
	
	private function prepareView($event, $page, $limit=20)
	{
		$user=$this->getUser();
		
		$comments = $this->getComments($event->eid, $page, $limit);
		$replies = $this->getReplies($event->eid, $comments, $page);
		$comment_count = $this->getCommentCount($event->eid);   
		$reply_count=$this->getReplyCount($event->eid);
		$first_level_comment_count = $comment_count - $reply_count;
		
		$this->view->event=$event;	
		$this->view->user = $user;
		$this->view->comments = $comments;        
        $this->view->replies  = $replies;
		$this->view->isEventAdmin = $this->_helper->modelLoader->isEventAdmin($event->eid, $user->uid);
        $this->view->comment_count = $comment_count;
		$this->view->first_level_comment_count = $first_level_comment_count;
		$this->view->current_page=$page;
	}
	
	private function getComments($eid, $page, $limit=20)
	{
		$key="event_comment_$eid"."_$limit";
		$data=$this->getCache($key);
		if ($data!==false)
		{
			if (isset($data[$page]))
			{
				return $data[$page];
			}
		}
		
		$c_model=$this->loadModel("Comment");
		$comments=$c_model->getEventComments($eid, $page, $limit);
		if (!is_array($data))
		{
			$data=array();
		}
		$data[$page]=$comments;
		$this->setCache($key, $data);
		return $comments;
	}
	
	private function getReplies($eid, $comments, $page){
        $key = "event_reply_$eid";
        $data = $this->getCache($key);
        if ($data) {
            if (isset($data[$page])) {
                return $data[$page];
            }
        }
        $cids = array();
        if (count($comments) > 0) {
            foreach ($comments as $c) {
                if ($c->changed > $c->created) {
                    $cids[] = $c->cid;
                }
            }
        }
        $commentModel = $this->loadModel('Comment');
        $replies = $commentModel->getReplies($cids);          
        if ( ! is_array($data)) {
            $data = array();
        }
        $data[$page] = $replies;
        $this->setCache($key, $data);
        return $replies;
    }
    
	private function getCommentCount($eid)
	{
		$key="event_comment_count_$eid";
		$data=$this->getCache($key);
		if ($data!==false)
		{
			if (isset($data["count"]))
			{
				return $data["count"];
			}
		}
		
		$c_model=$this->loadModel("Comment");
		$comment_count=$c_model->getEventCommentCount($eid);
		
		if (!is_array($data))
		{
			$data=array();
		}
		$data["count"]=$comment_count;
		$this->setCache($key, $data);
		return $comment_count;
	}
	
	private function getReplyCount($eid)
    {
        $key = "event_reply_count_$eid";
        $data = $this->getCache($key);
        if ($data !== FALSE) {
            if (isset($data['count'])) {
                return $data['count'];
            }
        }          
        $c_model = $this->loadModel("Comment");
        $comment_count = $c_model->getEventReplyCount($eid);        
        if (!is_array($data)) {
            $data=array();
        }
        $data['count'] = $comment_count;
        $this->setCache($key, $data);
        return $comment_count;    
    }
}

